package gamesys.games.particlesystem.effects {
	import gamesys.games.particlesystem.core.ParticleData;
	import gamesys.games.particlesystem.utils.Range;

	/**
	 * @author robertthurston
	 */
	public class LifeEffect implements IEffect {
		private var _life : Range;
		private var _fadeOutLevels : Range;
		private var _fadeInLevels : Range;
		private var _fadeInEnd : Number;
		private var _fadeInLevelsValue : Number;
		private var _fadeOutLevelsValue : Number;

		public function LifeEffect(life : Range, fadeInLevels : Range = null, fadeOutLevels : Range = null) {
			_life = life;
			_fadeInLevels = fadeInLevels;
			_fadeOutLevels = fadeOutLevels;
		}

		public function reset(particleData : ParticleData) : void {
			particleData.life = _life.range;
			particleData.alphaFade = 1;

			if (_fadeInLevels) {
				_fadeInLevelsValue = _fadeInLevels.range;
				particleData.life += _fadeInLevelsValue;
			}

			if (_fadeOutLevels) {
				_fadeOutLevelsValue = _fadeOutLevels.range;
				particleData.life += _fadeOutLevelsValue;
			}

			_fadeInEnd = particleData.life - _fadeInLevelsValue;
		}

		public function update(particleData : ParticleData) : void {
			particleData.life--;

			if (particleData.life > _fadeInEnd) {
				particleData.alphaFade = 1 - ((particleData.life - _fadeInEnd) / _fadeInLevelsValue);
			} else if (particleData.life < _fadeOutLevelsValue) {
				particleData.alphaFade = particleData.life / _fadeOutLevelsValue;
			} else {
				particleData.alphaFade = 1;
			}
		}
	}
}
